// app.ts
App({
  globalData: {
    info: {
      img: '',
      name: '未登录',
      phone: '',
      sex: 1,
      openid: ''
    },

    history: [],
    status: false,
    // url: 'https://bulang.mynatapp.cc/',
    url: 'http://192.168.3.190:7001/'

  },
  login_info() {
    const that = this;
    wx.login({
      success(res) {
        console.log(res)
        wx.getUserInfo({
          success: function (res) {
            console.log(res)
          }
        })
        if (res.code) {
          console.log(res.code)
          //发起网络请求
          wx.request({
            url: `${that.globalData.url}api/login`,
            data: {
              code: res.code
            },
            method: 'POST',
            success(res: { [proName: string]: any }) {
              console.log(res)
              console.log(res.data.data)
              that.globalData.info.openid = res.data.data;

            }
          })
        } else {
          console.log('登录失败！' + res.errMsg)

        }
      }
    })
  },



  login() {
    this.login_info();
    return new Promise((reslove, reject) => {
      wx.getUserProfile({
        desc: '资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          if (res) {
            console.log(res);
            this.globalData.info.name = res.userInfo.nickName
            this.globalData.info.sex = res.userInfo.gender
            this.globalData.info.img = res.userInfo.avatarUrl
            this.globalData.status = true
            console.log(this.globalData.info)
            wx.showToast({
              title: '登录成功',
              icon: 'success',
              duration: 2000
            })
            this.postUser();
            reslove(1)
          } else {
            wx.showToast({
              title: '登录失败',
              icon: 'error',
              duration: 2000
            })
            reject(0)
          }

        }
      })
    })
  },
  postUser() {
    const that=this
    const data=this.globalData.info;
    console.log(data)
    wx.request({
      url: `${that.globalData.url}api/user`,
      method:'POST',
      data,
      success(res: { data: { code: 0, data: { data: { id: number, news_image: string, news_name: string }[] }[] } }) {
        console.log(res)
      },
    })
  }
})

